/**
 * 
 */
package com.fox.webapp.persistent.impl;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;

import com.fox.webapp.domain.Broker;
import com.fox.webapp.persistent.custom.BrokerRepositoryCustom;

/**
 * @author yockii
 *
 */
public class BrokerRepositoryImpl implements BrokerRepositoryCustom {

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Override
	public Broker updateBroker(Broker broker) {
		Update update = new Update();
		if(StringUtils.hasText(broker.getName())){
			update.set("name", broker.getName());
		}
		if(StringUtils.hasText(broker.getBrokerDesc())){
			update.set("brokerDesc", broker.getBrokerDesc());
		}
		if(StringUtils.hasText(broker.getBrokerImgUrl())){
			update.set("brokerImgUrl", broker.getBrokerImgUrl());
		}
		if(StringUtils.hasText(broker.getRegulationInfo())){
			update.set("regulationInfo", broker.getRegulationInfo());
		}
		if(StringUtils.hasText(broker.getRefLink()) && broker.getRefLink().startsWith("http")){
			update.set("refLink", broker.getRefLink());
		}
		if(StringUtils.hasText(broker.getSpread())){
			update.set("spread", broker.getSpread());
		}
		if(broker.getActive() != null){
			update.set("active", broker.getActive());
		}
		if(broker.getMaxLeverage() != null){
			update.set("maxLeverage", broker.getMaxLeverage());
		}
		if(broker.getMinOpen() != null){
			update.set("minOpen", broker.getMinOpen());
		}
		if(broker.getMinTrade() != null){
			update.set("minTrade", broker.getMinTrade());
		}
		if(broker.getOrder() != null){
			update.set("order", broker.getOrder());
		}
		
		if(StringUtils.hasText(broker.getCountry())){
			update.set("country", broker.getCountry());
		}
		if(StringUtils.hasText(broker.getFounded())){
			update.set("founded", broker.getFounded());
		}
		if(broker.getHasChinese() != null){
			update.set("hasChinese", broker.getHasChinese());
		}
		if(broker.getHasChinaOffice() != null){
			update.set("hasChinaOffice", broker.getHasChinaOffice());
		}
		if(broker.getMaxTrade() != null){
			update.set("maxTrade", broker.getMaxTrade());
		}
		if(broker.getUnionPay() != null){
			update.set("unionPay", broker.getUnionPay());
		}
		if(StringUtils.hasText(broker.getTradePlatform())){
			update.set("tradePlatform", broker.getTradePlatform());
		}
		if(StringUtils.hasText(broker.getTradeKind())){
			update.set("tradeKind", broker.getTradeKind());
		}
		if(StringUtils.hasText(broker.getContact())){
			update.set("contact", broker.getContact());
		}
		
		return mongoTemplate.findAndModify(query(where("id").is(broker.getId())), update, FindAndModifyOptions.options().returnNew(true), Broker.class);
	}

}
